今天我們的目標是把圖中的初始狀態建立起來。
分析上圖可以看到整個場景可以歸納為 一個地圖 加上 三種物件,三種物件分別是 玩家、怪物、掉落物,地圖則負責記錄三種物件之間的位置關係。因此我們可以先利用物件導向的技巧來建立模型。
新增一個 typescript 專案 - 建立一個喜歡的資料夾並在裡面輸入以下指令
npm init -y
npm i -D typescript
npm i uuid
npx tsc --init
調整 tsconfig
"outDir": "./out",
"rootDir": "./src"
調整 package.json
"scripts": {
"start": "tsc && node ./out/index.js",
},
在 src/models/item.ts
建立三個物件,他們各自有甚麼行為或屬性等之後再加
import * as uuid from "uuid";
export class BaseItem {
id: string = uuid.v4();
name: string;
constructor(name: string) {
this.name = name;
}
}
export class Player extends BaseItem {
constructor(name: string) {
super(name);
}
}
export class Monster extends BaseItem {
constructor(name: string) {
super(name);
}
}
export class Dropped extends BaseItem {
constructor(name: string) {
super(name);
}
}
然後在 src/models/map.ts
建立一個地圖物件,三個維度分別代表 列 (row) = X軸
欄 (column) = Y軸
格 (cell) = 具體位置
。一個 cell 可以同時容納多個物件。
import { Dropped, Monster, Player } from "./item";
export type GridItem = Player | Monster | Dropped;
export class Map {
name: string;
grid: GridItem[][][]; // row > column > items
constructor(name: string, options?: { rows?: number; colums?: number }) {
const rows = options?.rows ?? 1; // 預設 1 列
const colums = options?.colums ?? 100; // 預設 100 欄
this.name = name;
this.grid = new Array(rows) // 預設全空
.fill(null)
.map(() => new Array(colums).fill(null).map(() => []));
}
// 透過這個函式增加物件到地圖上
add(player: GridItem, position: { x: number; y: number }) {
const { x, y } = position;
this.grid[x][y].push(player);
}
}
生成地圖
import { Map } from "./models/map";
import { Monster, Player } from "./models/item";
const map = new Map("森林小徑1");
map.add(new Player("煞氣a刀賊"), { x: 0, y: 99 });
map.add(new Player("乂正義黑騎乂"), { x: 0, y: 0 });
map.add(new Monster("紅寶"), { x: 0, y: 50 });
map.add(new Monster("藍寶"), { x: 0, y: 70 });
console.log(map);
console.log(map.grid);
結果
Map {
name: '森林小徑1',
grid: [
[
[Array], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [Array], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [Array], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [],
[], [], [], [Array]
]
]
}
[
[
[ [Player] ], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[ [Monster] ], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[ [Monster] ], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [],
[], [], [], [], [ [Player] ]
]
]